import axios from 'axios'
import router from '@/router'

const apiClient = axios.create({
  baseURL: process.env.VUE_APP_API_BASE || 'http://localhost:8080/api',
  timeout: 15000
})

apiClient.interceptors.request.use(
  config => {
    const token = window.localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

apiClient.interceptors.response.use(
  response => response.data,
  error => {
    const status = error && error.response ? error.response.status : 0
    if (status === 401) {
      if (typeof window !== 'undefined' && window.localStorage) {
        window.localStorage.removeItem('token')
      }
      if (router.currentRoute && router.currentRoute.path !== '/login') {
        router.replace({ path: '/login', query: { redirect: router.currentRoute.fullPath || '/' } })
      }
    }
    return Promise.reject(error)
  }
)

export default apiClient


